<template>
  <div>
    <div class="tools-div">
      <el-button type="success" size="small" @click="handleShowAddSpec">
        添 加
      </el-button>
    </div>

    <el-table :data="list" style="width: 100%">
      <el-table-column prop="specName" label="规格名称" />
      <el-table-column label="规格值" #default="scope">
        <div
          v-for="(item1, index1) in scope.row.specValue"
          :key="index1"
          style="padding: 5px; margin: 0;width: 100%;"
        >
          {{ item1.key }}：
          <span
            v-for="(item2, index2) in item1.valueList"
            :key="index2"
            class="div-atrr"
          >
            {{ item2 }}
          </span>
        </div>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" align="center" width="200" #default="scope">
        <el-button
          type="primary"
          size="small"
          @click="handleShowEditDialog(scope.row)"
        >
          修改
        </el-button>
        <el-button type="danger" size="small" @click="handleDelete(scope.row)">
          删除
        </el-button>
      </el-table-column>
    </el-table>

    <el-pagination
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next"
      :total="total"
    />

    <!-- 添加/修改 规格的对话框 -->
    <div>
      <el-dialog v-model="dialogVisible" title="添加或修改" width="40%">
        <el-form label-width="120px">
          <el-form-item label="规格名称">
            <el-input v-model="productSpec.specName" />
          </el-form-item>
          <el-form-item>
            <el-button
              size="default"
              type="success"
              @click="productSpec.specValue.push({})"
            >
              添加新规格
            </el-button>
          </el-form-item>
          <el-form-item
            label=""
            v-for="(item, index) in productSpec.specValue"
            :key="index"
          >
            <el-row>
              <el-col :span="10">
                <el-input
                  v-model="item.key"
                  placeholder="规格"
                  style="width: 90%;"
                />
              </el-col>
              <el-col :span="10">
                <el-input
                  v-model="item.valueList"
                  placeholder="规格值(如:白色,红色)"
                  style="width: 90%;"
                />
              </el-col>
              <el-col :span="4">
                <el-button
                  size="default"
                  type="danger"
                  @click="productSpec.specValue.splice(index, 1)"
                >
                  删除
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item align="right">
            <el-button type="primary" @click="handleSaveOrUpdate">
              提交
            </el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {
  GetPage,
  DeleteById,
  SaveProductSpec,
  UpdateProductSpec,
} from '@/api/productSpec'
import { ElMessage, ElMessageBox } from 'element-plus'
// ------------------ 新增/更新 规格
let dialogVisible = ref(false)
//对话框绑定数据
let productSpec = ref({
  specName: '',
  specValue: [],
})
//添加按钮事件函数：弹出新增商品规格的对话框
const handleShowAddSpec = () => {
  //清空缓存
  productSpec.value = {
    specName: '',
    specValue: [],
  }
  dialogVisible.value = true
}

//新增：
const handleSave = async () => {
  //提交新增请求
  if (!productSpec.value.specName || !productSpec.value.specValue) {
    ElMessage.warning('请输入商品规格数据')
    return
  }
  // 需要将productSpec.value.specValue转换成json字符串提交到后端，通过clone一个新的对象进行实现
  const productSpecClone = JSON.parse(JSON.stringify(productSpec.value))

  // 将productSpecClone.specValue.valueList转换成数组，因为后端需要的数组格式的数据[{"key":"内存","valueList":["8G","18G","32G"]}]
  // v-model绑定的数据模型为字符串
  productSpecClone.specValue.forEach(item => {
    item.valueList = item.valueList.split(',')
  })
  productSpecClone.specValue = JSON.stringify(productSpecClone.specValue)

  console.log(productSpecClone)

  // 提交表单
  await SaveProductSpec(productSpecClone)

  dialogVisible.value = false
  ElMessage.success('操作成功')
  fetchData()
}

//提交按钮事件函数
const handleSaveOrUpdate = () => {
  if (productSpec.value.id) {
    //更新
    handleUpdate()
  } else {
    //新增
    handleSave()
  }
}
//提交按钮更新
const handleUpdate = async () => {
  //后端深拷贝也会采用类似的方式：将对象转为json字符串  再转为java对象
  // 需要将productSpec.value.specValue转换成json字符串提交到后端，通过clone一个新的对象进行实现
  const productSpecClone = JSON.parse(JSON.stringify(productSpec.value))

  // 将productSpecClone.specValue.valueList转换成数组，因为后端需要的数组格式的数据[{"key":"内存","valueList":["8G","18G","32G"]}]
  // v-model绑定的数据模型为字符串
  productSpecClone.specValue.forEach(item => {
    console.log(typeof item.valueList)
    if (typeof item.valueList === 'string') {
      // 针对规格数据修改完毕以后数据类型有可能会变成string，针对string类型的数据将其转换成数组
      item.valueList = item.valueList.split(',')
    }
  })
  productSpecClone.specValue = JSON.stringify(productSpecClone.specValue)

  // 提交表单
  await UpdateProductSpec(productSpecClone)

  dialogVisible.value = false
  ElMessage.success('操作成功')
  fetchData()
}
//更新按钮事件函数：弹出更新的对话框 回显要更新的数据
const handleShowEditDialog = row => {
  productSpec.value = { ...row }
  dialogVisible.value = true
}

// ------------------ 新增/更新 规格==

//-----删除
const handleDelete = row => {
  ElMessageBox.confirm(
    `此操作将永久删除记录【${row.specName}】, 是否继续?`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    //点击确认按钮
    .then(async () => {
      await DeleteById(row.id)
      ElMessage.success('删除成功')
      fetchData()
    })
    //点击取消按钮
    .catch(() => {
      ElMessage.info('取消删除')
    })
}
//-------删除===
//---- 分页数据
let pageNum = ref(1)
let pageSize = ref(3)
const total = ref(0)

//---------分页数据===
onMounted(() => {
  fetchData()
})
const fetchData = async () => {
  const { data } = await GetPage(pageNum.value, pageSize.value)
  if (data.list) {
    data.list.forEach(spec => {
      spec.specValue = JSON.parse(spec.specValue)
      console.log(spec)
    })
  }

  list.value = data.list
  total.value = data.total
}

// 表格数据模型
const list = ref([
  {
    id: 2,
    createTime: '2023-05-06 12:56:08',
    specName: '笔记本电脑',
    specValue: [{ key: '内存', valueList: ['8G', '18G', '32G'] }],
  },
  {
    id: 1,
    createTime: '2023-05-06 12:40:22',
    specName: '小米手机',
    specValue: [
      { key: '颜色', valueList: ['白色', '红色', '黑色'] },
      { key: '内存', valueList: ['8G', '18G'] },
    ],
  },
])
</script>

<style scoped>
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.div-atrr {
  padding: 5px 10px;
  margin: 0 10px;
  background-color: powderblue;
  border-radius: 10px;
}
</style>
